#include "TrajFileCreator.h"



PointTraj::PointTraj(double latitude, double longitude, double altitude, double timestamp)
{
	this->latitude = latitude;
	this->longitude = longitude;
	this->altitude = altitude;
	this->timestamp = timestamp;

}
PointTraj::~PointTraj(void){

}


TrajFileCreator::TrajFileCreator()
{


	char repertory[20];
	cout << "Begin split files !\n";
	//cin >> repertory;
	
	//windows types because dirent.h doesn't exist in Visual Studio...
	   WIN32_FIND_DATA FindFileData;
	   HANDLE hFind;

	  
	  // _tprintf (TEXT("Target file is %s\n"),repertory);
	   hFind = FindFirstFile("*", &FindFileData);


	   if (hFind == INVALID_HANDLE_VALUE) 
	   {
		  printf ("FindFirstFile failed (%d)\n", GetLastError());
		  return;
	   } 
	   else 
	   {
		   
		   
		   //skip useless repertories
		   string nameRep = FindFileData.cFileName;
		   while(nameRep == "." || nameRep == ".."|| nameRep == ".svn"){
				FindNextFile(hFind, &FindFileData);
				if (hFind == INVALID_HANDLE_VALUE) 
				{
					printf ("FindFirstFile failed (%d)\n", GetLastError());
					return;
				} 
				nameRep = FindFileData.cFileName;
				
		   }

		   do{

			   //we get the first user file with datas
			  _tprintf (TEXT("The file found is %s\n"), FindFileData.cFileName);
		  

			  //now go inside and enter the trajectory file..
			   WIN32_FIND_DATA FindFileDataInUser;
			   HANDLE hFindInUser;

			   //create the path for the repertory
			   char* path = FindFileData.cFileName;
		   
			   strcat(path, "\\" );
			   strcat(path, "Trajectory");


			   _tprintf (TEXT("Target file is %s\n"), path);
			   hFindInUser = FindFirstFile(path, &FindFileDataInUser);
			   if (hFindInUser == INVALID_HANDLE_VALUE) 
			   {
				  printf ("FindFirstFile failed (%d)\n", GetLastError());
				  return;
			   } 
			   else 
			   {
				   char basePath[255];
				   strcpy(basePath, path);

				   strcat(path, "\\" );
				   strcat(path, "*" );


			   
				   WIN32_FIND_DATA FindFileDataInTraj;
				   HANDLE hFindInTraj;

				   _tprintf (TEXT("Target file is %s\n"), path);

				   //take first file
				   hFindInTraj = FindFirstFile(path, &FindFileDataInTraj);


				   if (hFindInTraj == INVALID_HANDLE_VALUE) 
				   {
					  printf ("FindFirstFile failed (%d)\n", GetLastError());
					  return;
				   } 
				   else 
				   {

					   //skip useless repertories
					   nameRep = FindFileDataInTraj.cFileName;
					   while(nameRep == "." || nameRep == ".."|| nameRep == ".svn"){
							if(FindNextFile(hFindInTraj, &FindFileDataInTraj)){
								if (hFind == INVALID_HANDLE_VALUE) 
								{
									printf ("FindFirstFile failed (%d)\n", GetLastError());
									return;
								} 
								nameRep = FindFileDataInTraj.cFileName;
							}
					   }

				   
					   char pathFile[255];
				   
				   


					   int fileCounter = 1;
					   //same with all the other ones
					   do{

							//path for the current file
							strcpy(pathFile, basePath);
							//create the path
							strcat(pathFile, "\\");
							strcat(pathFile, FindFileDataInTraj.cFileName);

							//have to be const for the constructor of trajectory
							const char * fileName = pathFile;
						
							int sizeOfName = strlen(fileName);
						


							if( sizeOfName == 33){
								//split
								findNewTraj(fileName);
							}
							fileCounter++;
					   }while(FindNextFile(hFindInTraj, &FindFileDataInTraj));
				   
					  cout << fileCounter << " trajectories have been created\n";

					   FindClose(hFindInTraj);
				   }
			   

				   FindClose(hFindInUser);
			   }
		   
		   }while(FindNextFile(hFind, &FindFileData));

		  FindClose(hFind);
	   }

	   cout << "End\n";

}


TrajFileCreator::~TrajFileCreator(void)
{
}



void TrajFileCreator::findNewTraj(const char* _file){

	ifstream pFile;
	char buffer[255];
	char* splitedString;
	double latitud;
	double longitud;
	double altitud;
	double timestam;

	int trajNum = 1;
	string headerTraj = "";
	string content = ""; 
	string filePathWithoutExt = "";


	char tempNameFile[50];
	strcpy(tempNameFile, _file);

	char* splitedPath = strtok(tempNameFile, ".");
	filePathWithoutExt += splitedPath;

	

	//open a file and read it : works   
	pFile.open(_file);
	if (!pFile.is_open()) perror ("Error opening file");
	else
	{
		 
		int i;
		for(i=0;i<6;i++){
			//skip the 6 first lines
			if(!pFile.eof()){
				pFile.getline(buffer, 255);
				headerTraj += buffer;
				headerTraj += "\n";
			}
		}

		

		PointTraj p = PointTraj(0,0,0,0);
		PointTraj pOld = PointTraj(0,0,0,0);
		int j=7;
		char tempBuffLine[255];

		while( !pFile.eof())
		{
			//we count to only get the right informations
			i=0;

			pFile.getline(buffer, 255);
			//keep the line to add it after if it's a good one
			strcpy(tempBuffLine, buffer);

			splitedString = strtok(buffer, ",");
			while (splitedString != NULL){				
				if(i == 4)
					timestam = atof(splitedString);				

				i++;
				//repeat the call until the end
				splitedString = strtok (NULL, ",");
			}
				
			
			//if not the first point
			if(p.getTimestamp() != 0){
				pOld = p;
			}		
			p = PointTraj(0, 0, 0, timestam);

			if(pOld.getTimestamp() != 0){
				//if more than 15 minutes between 2 points (value in days)
				if(((p.getTimestamp() - pOld.getTimestamp()) > 0.01) || pFile.eof()){
					
					
					
					//create new file with same name+numFile
					string nameOfNewFile = "";
					nameOfNewFile += filePathWithoutExt;

					char nbTrajCurrent[10];
					itoa(trajNum, nbTrajCurrent, 10);

					nameOfNewFile += nbTrajCurrent;
					nameOfNewFile += ".plt";

					ofstream out(nameOfNewFile);

					//put inside header + content
					out << headerTraj << content;

					out.close();

					//init content for next file
					content = "";
					

					trajNum++;

				}

			}
			content += tempBuffLine;
			content += "\n";
		
				
			
			
				
		}
			
		

		pFile.close();
			
		remove(_file);
			 
	}

	

}
